<template>
  <div class="app-container">
    <!-- 饼图 -->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card shadow="never">
          <div ref="sourceChart" style="height: 260px;"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="never">
          <div ref="assessmentChart" style="height: 260px;"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="never">
          <div ref="closureChart" style="height: 260px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮和主表格 -->
    <div class="table-container">
      <div class="table-actions">
        <el-button type="primary" @click="handleRefresh"><el-icon><Refresh /></el-icon>刷新</el-button>
        <el-button type="primary" @click="handleExport"><el-icon><Download /></el-icon>导出</el-button>
        <el-button type="primary" @click="handleShowClosure"><el-icon><Finished /></el-icon>结案</el-button>
      </div>
      <el-table
        :data="tableData"
        style="width: 100%"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="organization" label="组织结构" width="250" />
        <el-table-column prop="total" label="总人数" />
        <el-table-column prop="normal" label="正常适应" />
        <el-table-column prop="mild" label="轻度关注" />
        <el-table-column prop="focus" label="重点关注" />
        <el-table-column prop="highRisk" label="高度风险" />
        <el-table-column prop="crisis" label="危机状态" />
      </el-table>
    </div>

    <!-- 结案对话框 -->
    <el-dialog v-model="closureDialogVisible" title="结案" width="80%">
      <div class="closure-filter-container">
        <el-form :inline="true" :model="closureSearchForm">
          <el-form-item label="姓名">
            <el-input v-model="closureSearchForm.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="账号">
            <el-input v-model="closureSearchForm.account" placeholder="请输入账号" />
          </el-form-item>
          <el-form-item label="组织结构">
            <!-- Tree select for organization -->
          </el-form-item>
          <el-form-item label="时间">
            <el-date-picker
              v-model="closureSearchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item label="结案状态">
            <el-select v-model="closureSearchForm.status" placeholder="请选择状态">
              <el-option label="已结案" value="closed" />
              <el-option label="未结案" value="open" />
            </el-select>
          </el-form-item>
          <el-form-item label="干预类型">
            <el-select v-model="closureSearchForm.interventionType" placeholder="请选择干预类型">
              <el-option label="高关怀" value="highCare" />
              <el-option label="危机干预" value="crisis" />
              <el-option label="常规辅导" value="routine" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleClosureSearch">查询</el-button>
            <el-button @click="handleClosureReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="closureTableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)" style="width: 100%">
        <!-- Table columns same as main table -->
        <el-table-column prop="organization" label="组织结构" width="180" />
        <el-table-column prop="total" label="总人数" />
        <el-table-column prop="normal" label="正常适应" />
        <el-table-column prop="mild" label="轻度关注" />
        <el-table-column prop="focus" label="重点关注" />
        <el-table-column prop="highRisk" label="高度风险" />
        <el-table-column prop="crisis" label="危机状态" />
        <el-table-column prop="interventionType" label="干预类型">
          <template #default="scope">
            <el-tag v-if="scope.row.interventionType === 'highCare'" type="warning">高关怀</el-tag>
            <el-tag v-else-if="scope.row.interventionType === 'crisis'" type="danger">危机干预</el-tag>
            <el-tag v-else-if="scope.row.interventionType === 'routine'" type="success">常规辅导</el-tag>
            <el-tag v-else type="info">未分类</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="closureReason" label="结案原因" />
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="closureTableData.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import { Refresh, Download, Finished } from '@element-plus/icons-vue';
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import { ElMessage } from 'element-plus';

// Chart refs
const sourceChart = ref(null);
const assessmentChart = ref(null);
const closureChart = ref(null);

// Main table data
const tableData = ref([
  {
    id: 1,
    organization: '计算机学院',
    total: 100,
    normal: 75,
    mild: 15,
    focus: 7,
    highRisk: 2,
    crisis: 1,
    children: [
      {
        id: 11,
        organization: '计算机技术',
        total: 50,
        normal: 38,
        mild: 8,
        focus: 3,
        highRisk: 1,
        crisis: 0,
      },
      {
        id: 12,
        organization: '大数据工程',
        total: 50,
        normal: 37,
        mild: 7,
        focus: 4,
        highRisk: 1,
        crisis: 1,
      },
    ],
  },
  {
    id: 2,
    organization: '软件学院',
    total: 120,
    normal: 90,
    mild: 18,
    focus: 8,
    highRisk: 3,
    crisis: 1,
  },
]);

// Closure dialog
const closureDialogVisible = ref(false);
const closureSearchForm = ref({
  name: '',
  account: '',
  organization: '',
  dateRange: '',
  status: '',
  interventionType: '',
});
const closureTableData = ref([
  {
    id: 101,
    organization: '计算机学院',
    total: 50,
    normal: 38,
    mild: 8,
    focus: 3,
    highRisk: 1,
    crisis: 0,
    interventionType: 'highCare',
    closureReason: '学生情绪稳定，已完成心理辅导'
  },
  {
    id: 102,
    organization: '计算机学院',
    total: 45,
    normal: 35,
    mild: 7,
    focus: 2,
    highRisk: 1,
    crisis: 0,
    interventionType: 'routine',
    closureReason: '学生适应环境，问题已解决'
  },
  {
    id: 103,
    organization: '软件学院',
    total: 60,
    normal: 45,
    mild: 10,
    focus: 3,
    highRisk: 1,
    crisis: 1,
    interventionType: 'crisis',
    closureReason: '危机已解除，转为常规辅导'
  },
  {
    id: 104,
    organization: '人工智能学院',
    total: 55,
    normal: 42,
    mild: 8,
    focus: 4,
    highRisk: 1,
    crisis: 0,
    interventionType: 'routine',
    closureReason: '学业问题已解决'
  },
  {
    id: 105,
    organization: '人工智能学院',
    total: 48,
    normal: 38,
    mild: 6,
    focus: 3,
    highRisk: 1,
    crisis: 0,
    interventionType: 'highCare',
    closureReason: '已转介至校外专业机构'
  }
]);
const currentPage = ref(1);
const pageSize = ref(10);

const handleSizeChange = (val) => {
  pageSize.value = val;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

const handleRefresh = () => {
  // Refresh logic
};

const handleExport = () => {
  // 准备导出数据
  const exportData = [];
  
  // 递归处理数据，包括子级
  const processData = (items, level = 0) => {
    items.forEach(item => {
      // 创建当前项的数据副本，只包含需要的字段
      const exportItem = {
        organization: item.organization,
        total: item.total,
        normal: item.normal,
        mild: item.mild,
        focus: item.focus,
        highRisk: item.highRisk,
        crisis: item.crisis
      };
      
      // 为子级添加缩进标识
      if (level > 0) {
        exportItem.organization = '  '.repeat(level) + '└ ' + exportItem.organization;
      }
      
      // 添加到导出数据
      exportData.push(exportItem);
      
      // 递归处理子级
      if (item.children && item.children.length > 0) {
        processData(item.children, level + 1);
      }
    });
  };
  
  // 处理所有数据
  processData(tableData.value);
  
  // 创建工作簿
  const workbook = XLSX.utils.book_new();
  
  // 将数据转换为工作表
  const worksheet = XLSX.utils.json_to_sheet(exportData);
  
  // 设置列宽
  const columnWidths = [
    { wch: 30 }, // 组织结构 - 增加宽度以适应缩进
    { wch: 10 }, // 总人数
    { wch: 10 }, // 正常适应
    { wch: 10 }, // 轻度关注
    { wch: 10 }, // 重点关注
    { wch: 10 }, // 高度风险
    { wch: 10 }, // 危机状态
  ];
  worksheet['!cols'] = columnWidths;
  
  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, '预警干预数据');
  
  // 生成Excel文件并下载
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
  saveAs(blob, '预警干预数据.xlsx');
  
  // 提示用户
  ElMessage.success('导出成功');
};

const handleShowClosure = () => {
  closureDialogVisible.value = true;
};

const handleClosureSearch = () => {
  // 获取搜索条件
  const { name, account, organization, dateRange, status, interventionType } = closureSearchForm.value;
  
  // 过滤数据
  const filteredData = originalClosureData.value.filter(item => {
    // 姓名筛选
    if (name && !item.organization.includes(name)) {
      return false;
    }
    
    // 账号筛选
    if (account && !String(item.id).includes(account)) {
      return false;
    }
    
    // 组织结构筛选
    if (organization && item.organization !== organization) {
      return false;
    }
    
    // 结案状态筛选
    if (status) {
      // 假设lifted > 0表示已结案
      const isClosed = item.lifted > 0;
      if ((status === 'closed' && !isClosed) || (status === 'open' && isClosed)) {
        return false;
      }
    }
    
    // 干预类型筛选
    if (interventionType && item.interventionType !== interventionType) {
      return false;
    }
    
    // 日期范围筛选 (这里假设没有具体日期字段，实际应用中需要根据实际数据结构调整)
    
    return true;
  });
  
  // 更新表格数据
  closureTableData.value = filteredData;
  
  // 重置分页到第一页
  currentPage.value = 1;
  
  // 提示用户
  ElMessage.success(`查询到 ${filteredData.length} 条记录`);
};

const handleClosureReset = () => {
  // 重置搜索表单
  closureSearchForm.value = {
    name: '',
    account: '',
    organization: '',
    dateRange: '',
    status: '',
    interventionType: ''
  };
  
  // 恢复原始数据
  closureTableData.value = JSON.parse(JSON.stringify(originalClosureData.value));
  
  // 重置分页
  currentPage.value = 1;
  
  // 提示用户
  ElMessage.info('已重置搜索条件和结果');
};

// Chart initialization
const initCharts = () => {
  const colors = ['#5470c6', '#91cc75', '#fac858'];

  // Source Chart
  const sourceChartInstance = echarts.init(sourceChart.value);
  sourceChartInstance.setOption({
    title: {
      text: '预警用户来源',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'right',
      top: 'center',
      itemWidth: 14,
      itemHeight: 14,
      data: ['自主求助', '辅导员上报', '量表筛查']
    },
    series: [
      {
        name: '来源',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '20',
            fontWeight: 'bold',
            formatter: '{b}\n{c}'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 335, name: '自主求助' },
          { value: 310, name: '辅导员上报' },
          { value: 234, name: '量表筛查' },
        ],
      },
    ],
    color: colors
  });

  // Assessment Chart
  const assessmentChartInstance = echarts.init(assessmentChart.value);
  assessmentChartInstance.setOption({
    title: {
      text: '预警用户评估情况',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'right',
      top: 'center',
      itemWidth: 14,
      itemHeight: 14,
      data: ['已评估', '未评估']
    },
    series: [
      {
        name: '评估情况',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '20',
            fontWeight: 'bold',
            formatter: '{b}\n{c}'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 500, name: '已评估' },
          { value: 100, name: '未评估' },
        ],
      },
    ],
    color: colors
  });

  // Closure Chart
  const closureChartInstance = echarts.init(closureChart.value);
  closureChartInstance.setOption({
    title: {
      text: '预警用户结案情况',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'right',
      top: 'center',
      itemWidth: 14,
      itemHeight: 14,
      data: ['已结案', '未结案']
    },
    series: [
      {
        name: '结案情况',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '20',
            fontWeight: 'bold',
            formatter: '{b}\n{c}'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 400, name: '已结案' },
          { value: 200, name: '未结案' },
        ],
      },
    ],
    color: colors
  });
};

// 保存原始数据备份，用于重置
const originalClosureData = ref([]);

// 在组件挂载时保存原始数据
onMounted(() => {
  initCharts();
  // 保存结案数据的原始副本
  originalClosureData.value = JSON.parse(JSON.stringify(closureTableData.value));
});
</script>

<style scoped>
.app-container {
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
}
.app-container > .el-row > .el-col > .el-card {
  border: none;
  box-shadow: none;
}
.table-container {
  margin-top: 20px;
}
.table-actions {
  margin-bottom: 10px;
}
.closure-filter-container {
  margin-bottom: 20px;
}
</style>
